﻿using System;
using System.Linq;
using System.Linq.Expressions;

namespace SBToolkit.Collections
{
    /// <summary>
    /// Extends <see cref="IQueryable{T}"/> with additional functionality.
    /// </summary>
    public static class QueryableHelper
    {
        /// <summary>
        /// Performs custom paging for the specified query.
        /// </summary>
        /// <typeparam name="T"><see cref="Type" /> of the data source to be paged.</typeparam>
        /// <param name="query">The query to page.</param>
        /// <param name="pageNumber">Page number to fetch.</param>
        /// <param name="pageSize">Number of rows per page.</param>
        /// <returns>Page.</returns>
        public static IQueryable<T> Page<T>(this IQueryable<T> query, int pageNumber, int pageSize)
        {
            return query.Skip(pageNumber * pageSize).Take(pageSize);
        }

        /// <summary>
        /// Performs custom paging and sorting for the specified query.
        /// </summary>
        /// <typeparam name="T"><see cref="Type" /> of the data source to be paged.</typeparam>
        /// <typeparam name="TResult"><see cref="Type" /> of the sort column.</typeparam>
        /// <param name="query">The query to page and sort.</param>
        /// <param name="pageNumber">Page number to fetch.</param>
        /// <param name="pageSize">Number of rows per page.</param>
        /// <param name="sortExpression">Sorting expression.</param>
        /// <param name="isAsc">Sort ascending if <c>true</c>; otherwise descending.</param>
        /// <returns>Sorted page.</returns>
        public static IQueryable<T> Page<T, TResult>(this IQueryable<T> query, int pageNumber, int pageSize, Expression<Func<T, TResult>> sortExpression, bool isAsc)
        {
            if (sortExpression != null)
            {
                query = isAsc ? query.OrderBy(sortExpression) : query.OrderByDescending(sortExpression);
            }

            return query.Page(pageNumber, pageSize);
        }
    }
}